#!/bin/bash

# 多平台交叉编译脚本（使用 cross）
# 用法: ./build.sh [--release]

# 目标平台列表
TARGETS=(
    "aarch64-unknown-linux-gnu"
    "i686-unknown-linux-gnu"
    "riscv64gc-unknown-linux-gnu"
    "x86_64-unknown-linux-gnu"
)

# 项目名称，从 Cargo.toml 中获取
PROJECT_NAME=$(grep -o '^name = "[^"]*"' Cargo.toml | cut -d'"' -f2)

# 构建参数
BUILD_MODE=""
BUILD_DIR_SUFFIX="debug"
if [[ "$1" == "--release" ]]; then
    BUILD_MODE="--release"
    BUILD_DIR_SUFFIX="release"
    echo "构建 Release 版本"
else
    echo "构建 Debug 版本"
fi

# 检查 cross 是否安装
if ! command -v cross &> /dev/null; then
    echo "❌ 未找到 cross，请先安装：cargo install cross"
    exit 1
fi

# 确保项目名称已成功获取
if [ -z "$PROJECT_NAME" ]; then
    echo "❌ 无法从 Cargo.toml 中获取项目名称，请确保文件存在且格式正确。"
    exit 1
fi

# 准备打包目录
BUILD_OUTPUT_DIR="build"
if [ -d "$BUILD_OUTPUT_DIR" ]; then
    echo "清理旧的 $BUILD_OUTPUT_DIR 目录..."
    rm -rf "$BUILD_OUTPUT_DIR"
fi
mkdir -p "$BUILD_OUTPUT_DIR"

# 构建
FAILED_TARGETS=()
echo "开始使用 cross 构建..."
for target in "${TARGETS[@]}"; do
    echo ""
    echo "=== 构建目标: $target ==="
    cross build $BUILD_MODE --target "$target"
    
    if [ $? -eq 0 ]; then
        echo "✅ 成功构建: $target"

        # 处理编译成功后的文件
        DEST_DIR="$BUILD_OUTPUT_DIR/${PROJECT_NAME}_${target}"
        mkdir -p "$DEST_DIR"
        echo "创建目标文件夹: $DEST_DIR"

        # 复制二进制文件
        BINARY_SRC_PATH="target/$target/$BUILD_DIR_SUFFIX/$PROJECT_NAME"
        if [ -f "$BINARY_SRC_PATH" ]; then
            cp "$BINARY_SRC_PATH" "$DEST_DIR/"
            echo "复制可执行文件: $PROJECT_NAME"
        else
            echo "❌ 未找到可执行文件: $BINARY_SRC_PATH"
            continue
        fi

        # 复制 static 目录
        STATIC_SRC_PATH="static"
        if [ -d "$STATIC_SRC_PATH" ]; then
            cp -r "$STATIC_SRC_PATH" "$DEST_DIR/"
            echo "复制 'static' 目录"
        else
            echo "⚠️ 'static' 目录不存在，跳过复制"
        fi

        # 压缩文件夹
        ZIP_FILE="$BUILD_OUTPUT_DIR/${PROJECT_NAME}_${target}.zip"
        echo "正在压缩到: $ZIP_FILE"
        (cd "$BUILD_OUTPUT_DIR" && zip -r "../$ZIP_FILE" "${PROJECT_NAME}_${target}")
        
        echo "清理临时文件夹: $DEST_DIR"
        rm -rf "$DEST_DIR"

    else
        echo "❌ 构建失败: $target"
        FAILED_TARGETS+=("$target")
    fi
done

# 构建结果
echo ""
echo "=== 构建结果 ==="
if [ ${#FAILED_TARGETS[@]} -eq 0 ]; then
    echo "🎉 所有目标平台构建成功并已打包!"
else
    echo "⚠️ 以下目标平台构建失败:"
    for target in "${FAILED_TARGETS[@]}"; do
        echo "  - $target"
    done
    exit 1
fi

echo ""
echo "打包完成的文件位于:"
echo "  $BUILD_OUTPUT_DIR/"
